const express = require("express");
const app = express();
const userRouter = require("./router/user");
const userInfoRouter = require("./router/userinfo");
const artCateRouter = require("./router/artcate");
const articleRouter = require("./router/article");

//配置跨域的中间件， 以及解析表单数据的中间件
const cors = require("cors");
const joi = require("joi");
app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

//封装res.cc()函数， 捕获报错
app.use((req, res, next) => {
  res.cc = (err, status = 1) => {
    res.send({
      status,
      message: err instanceof Error ? err.message : err,
    });
  };

  next();
});

// 在注册路由之前配置解析token的中间件
const expressJWT = require("express-jwt");
const config = require("./config");
app.use(
  expressJWT({ secret: config.jwtSecretKey, algorithms: ["HS256"] }).unless({
    path: [/^\/api\//],
  })
);

// 测试路由
app.get("/", (req, res) => {
  res.send("home page");
});

// 注册路由模块
app.use("/api", userRouter);
app.use("/my", userInfoRouter);
app.use("/my/article", artCateRouter);
app.use("/my/article", articleRouter);

app.use((err, req, res, next) => {
  if (err instanceof joi.ValidationError) return res.cc(err);
  if (err.name === "UnauthorizedError") return res.cc("身份认证失败！");
  //未知的错误
  res.cc(err.message);
});

app.listen(80, () => {
  console.log("server is running at andreas project ");
});
